package com.weedsdream.app.floatWindow

import android.content.Intent
import android.content.res.Configuration
import android.graphics.PixelFormat
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.WindowManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.weedsdream.BaseActivity
import com.weedsdream.app.MainActivity
import com.weedsdream.app.compose.DrawBoardMainUi
import com.weedsdream.app.compose.scCenter
import com.weedsdream.base.R


/*Activity和Service浮窗实现方式几乎一致,但以下问题无法同时解决
 *问题1:Compose需要绑定savedInstanceState,Service中无法获取此变量，Service浮窗绑定其它Activity的savedInstanceState将导致该Activity不显示时浮窗无法正常运行
 *问题2:原生View不需要绑定savedInstanceState,但我既不会原生View,已经实现的Compose代码也要使用View重写一遍,复杂性高
 *问题3:同App中只能同时显示一个Activity，使用Activity浮窗，浮窗和应用主Activity同时只能显示一个*/
/**悬浮窗Activity*/
class FloatingWindowActivity : BaseActivity() {
    /**底层浮窗绘板*/
    private lateinit var fwBoard: Pair<ComposeView, WindowManager.LayoutParams>

    /**浮窗控制按钮*/
    private lateinit var fwButton: Pair<ComposeView, WindowManager.LayoutParams>

    companion object {
        /**启用悬浮窗
         * @param noPermission 没有权限时执行的内容*/
        fun openFloatWindow(noPermission: () -> Unit = {}) {
            if (Settings.canDrawOverlays(activity)) {
                //如果已经拥有权限，则启用悬浮窗
                Intent(activity, FloatingWindowActivity::class.java).apply {
                    activity.startActivity(this)
                }
            } else noPermission()
        }

        /**销毁悬浮窗*/
        fun destroyFloatWindow() {
            activity.finish()
        }
    }

    /**横竖屏切换时Ui尺寸变化，避免笔迹错位需要重赋值scCenter*/
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//切换为横屏
            scCenter = null
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {//切换为竖屏
            scCenter = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 添加底层悬浮窗
        fwBoard = fwBoard()
        windowManager.addView(fwBoard.first, fwBoard.second)
        //添加按钮浮窗
        fwButton = fwButton()
        windowManager.addView(fwButton.first, fwButton.second)
        //启用浮窗时自动回到桌面
        Intent(Intent.ACTION_MAIN).apply {
            addCategory(Intent.CATEGORY_HOME)
            setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(this)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        windowManager.removeView(fwBoard.first)
        windowManager.removeView(fwButton.first)
        //关闭悬浮窗时返回主界面
        Intent(activity, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(this)
        }
    }

    /**创建全屏浮窗背景*/
    private fun fwBoard(): Pair<ComposeView, WindowManager.LayoutParams> {
        //绑定生命周期
        val view = ComposeView(this).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                Box(
                    Modifier
                        .fillMaxSize()
                        .alpha(floatWindowAlpha / 100f)
                ) {
                    if (enableFloatBoard) DrawBoardMainUi(false)
                }
            }
            setViewTreeLifecycleOwner(this@FloatingWindowActivity)
            setViewTreeSavedStateRegistryOwner(this@FloatingWindowActivity)
        }
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, if (enableFloatBoard) {
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE //不获取焦点
            } else {
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE//手势穿透
            }, PixelFormat.TRANSLUCENT
        ).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                layoutInDisplayCutoutMode =//可用区域扩展到全屏
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
            }
        }
        return Pair(view, layoutParams)
    }


    /**创建浮窗控制按钮*/
    private fun fwButton(): Pair<ComposeView, WindowManager.LayoutParams> {
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, //
            WindowManager.LayoutParams.WRAP_CONTENT, //
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,  //不获取焦点
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START//初始位置
            x = BaseActivity.screenSize.x//初始放到尾部(Gravity.END会导致拖动时反向移动，不设置END)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                layoutInDisplayCutoutMode =//可用区域扩展到全屏
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
            }
        }
        // 绑定生命周期
        val view = ComposeView(this).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                Box(Modifier.size(50.dp)) {
                    Image(
                        painterResource(R.drawable.tp_logo), null, Modifier
                            .alpha(floatWindowAlpha / 100f)
                            .size(50.dp)
                    )
                    Text(
                        text = if (enableFloatBoard) "开" else "关", fontSize = 12.sp,
                        color = if (enableFloatBoard) androidx.compose.ui.graphics.Color.Blue else androidx.compose.ui.graphics.Color.DarkGray,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
            }
            setViewTreeLifecycleOwner(this@FloatingWindowActivity)
            setViewTreeSavedStateRegistryOwner(this@FloatingWindowActivity)

            var downTime = 0L//记录手指按下的时间，实现点击逻辑
            val clickTime = 200L//手指按下到抬起判定为点击的最大时间间隔
            var offsetX = 0//记录手指按下时view已经移动的距离，使拖动时浮窗纠正偏移位置紧随手指
            var offsetY = 0
            setOnTouchListener { view, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        view.performClick()
                        downTime = System.currentTimeMillis()
                        offsetX = layoutParams.x - event.rawX.toInt()
                        offsetY = layoutParams.y - event.rawY.toInt()
                        true
                    }

                    MotionEvent.ACTION_MOVE -> {
                        downTime = 0//移动以后必不是点击
                        layoutParams.x = event.rawX.toInt() + offsetX
                        layoutParams.y = event.rawY.toInt() + offsetY
                        windowManager.updateViewLayout(fwButton.first, fwButton.second)
                        true
                    }

                    MotionEvent.ACTION_UP -> {
                        if (System.currentTimeMillis() - downTime < clickTime) {//点击事件
                            enableFloatBoard = !enableFloatBoard
                            //更新绘板flags参数
                            fwBoard.second.flags = if (enableFloatBoard) {
                                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            } else {
                                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE //手势穿透
                            }
                            windowManager.updateViewLayout(fwBoard.first, fwBoard.second)
                        } else if (downTime != 0L) {//长按事件
                            Log.i("test", "长按")
                        } else {//拖动结束
                            Log.i("test", "拖动结束")
                        }
                        true
                    }

                    else -> false
                }
            }
        }

        return Pair(view, layoutParams)
    }
}